#include "qt.h"

qt::qt(QWidget *parent, Qt::WFlags flags): QMainWindow(parent, flags)
{
	ui.setupUi(this);

	driver = new FSFDriver(L"FsFilter", L"C:\\Windows\\System32\\Drivers\\FsFilter.sys");

	connect(ui.pushButtonAdd, SIGNAL(clicked()), this, SLOT(Add()));
	connect(ui.pushButtonImprove, SIGNAL(clicked()), this, SLOT(Improve()));
	connect(ui.pushButtonStart, SIGNAL(clicked()), this, SLOT(StartDriver()));
	connect(ui.actionLoad, SIGNAL(triggered()), this, SLOT(LoadFromFile()));
	connect(ui.actionSave, SIGNAL(triggered()), this, SLOT(SaveToFile()));
	connect(ui.actionExit, SIGNAL(triggered()), this, SLOT(close()));
	connect(ui.actionHints, SIGNAL(triggered()), this, SLOT(OpenHelp()));
	connect(ui.actionAbout, SIGNAL(triggered()), this, SLOT(ShowAbout()));
	connect(ui.actionClear, SIGNAL(triggered()), ui.comboBoxAdd, SLOT(clear()));
	connect(ui.comboBoxAdd, SIGNAL(currentIndexChanged(int)), this, SLOT(SetLabelText(int)));
	connect(ui.checkBoxOnOff, SIGNAL(stateChanged(int)), this, SLOT(Clear(int)));
}

void qt::SetLabelText(int index)
{
	if (index >= 0)
		ui.labelAdd->setText(str[ui.comboBoxAdd->currentIndex()]);
}

void qt::LoadFromFile()
{
	buff.LoadFromFile();

	str.clear();
	ui.comboBoxAdd->clear();
	
	for (int i = 0; i < buff.Size(); ++i)
	{
		str.push_back(QString::fromStdWString(buff.ReturnRule(i)));
		ui.comboBoxAdd->addItem(QString::fromStdWString(buff.ReturnName(i)));
	}
}

void qt::SaveToFile()
{
	buff.SaveToFile();
}

void qt::Add()
{
	QString name = ui.lineEditAddName->text();
	QString rule = ui.lineEditAddRule->text();
	
	if (name.length() == 0 || rule.length() == 0)
	{  
		QMessageBox::warning(0, "Warning!", "The Rule Is Empty!");
		return;
	}

	buff.Add(name.toStdWString(), rule.toStdWString());
	str.push_back(rule);
	
	ui.comboBoxAdd->addItem(name);
}

void qt::Improve()
{
	if (ui.comboBoxAdd->currentIndex() < 0)
	{  
		QMessageBox::warning(0, "Error!", "The Rule Didn't Exist!");
		return;
	}
		
	wchar_t* buffer = buff.ReturnBuffer(ui.comboBoxAdd->currentIndex());

	if (!driver->SendRule(buffer))
	{  
		QMessageBox::warning(0, "Error!", "The Rule Didn't Improved!");
		delete [] buffer;
		buffer = NULL;
		return;
	}

	delete [] buffer;
	buffer = NULL;
}

void qt::Clear(int on)
{
	if (ui.checkBoxOnOff->checkState())
		driver->Hiding(1);
	else
		driver->Hiding(0);
}

void qt::StartDriver()
{
	if (!driver->Start())
	{
		QMessageBox::warning(0, "Error!", "The Driver Cannot start!");
		return;
	}
}

void qt::OpenHelp()
{
	ShellExecute(0, L"open", L"help.doc", NULL, NULL, SW_SHOWNORMAL);
}

void qt::ShowAbout()
{
	QMessageBox::information(0, "About!", "File System Filter Driver\nAll rights reserved");
}

qt::~qt()
{
	driver->~FSFDriver();
}
